using Dapper;
using Dapper.Contrib.Extensions;
using Read.Models;
using Read.Utility;

namespace Read.Services
{
    public class AccountService : BaseService
    {
        public ResultData<AdminModel> loginCheck(AdminModel model)
        {
            using (var connection = GetConnection())
            {
                if (!string.IsNullOrEmpty(model.UserName) && !string.IsNullOrEmpty(model.Password))
                {
                    var sql = $"select * from `{Tables.Admin}` where username=@UserName";
                    var m = connection.QueryFirstOrDefault<AdminModel>(sql, new { UserName = model.UserName });
                    if (m != null)
                    {
                        //验证密码
                        var pwd = Tools.HasPassword(model.Password, m.Verify);
                        if (m.Password == pwd)
                        {
                            //更新登录时间
                            m.LastLoginIp = "127.0.0.1";
                            m.LastLoginTime = Tools.ToUnixTime();
                            connection.Update(m);
                            m.Password = string.Empty;
                            m.Verify = string.Empty;
                            return new ResultData<AdminModel>() { Code = 0, Result = true, Data = m, Message = "登录成功!" };
                        }
                        else return new ResultData<AdminModel>() { Code = 1, Result = false, Message = "用户密码错误!" };
                    }
                    else return new ResultData<AdminModel>() { Code = 2, Result = false, Message = "用户名不存在!" };
                }
                else return new ResultData<AdminModel>() { Code = 3, Result = false, Message = "请输入用户名或密码!" };
            }
        }
    }
}